package com.lagou.edu.controller;

import com.lagou.edu.pojo.User;
import com.lagou.edu.service.AuthService;
import com.lagou.edu.service.UserService;
import com.lagou.edu.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AuthService authService;

    /**
     * 注册接⼝，true成功，false失败
     */
    @RequestMapping("/register/{email}/{password}/{code}")
    public Boolean register(
            @PathVariable("email") String email,
            @PathVariable("password") String password,
            @PathVariable("code") String code) {
        return userService.register(email, password, code);
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，
     * false代表尚未注册
     */
    @RequestMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable("email") String email) {
        User user = userService.findByEmail(email);
        return user == null ? false : true;
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     */
    @RequestMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email,
                        @PathVariable("password") String password,
                        HttpServletResponse response) {
        String dbEmail = userService.login(email, password);

        if (dbEmail == null) {
            return "";
        }

        // 获取token
        String token = MD5Utils.encrypt(email, password);

        // 保存cookie
        setCookies(response, token);

        return dbEmail;
    }

    public void setCookies(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie("token", token);
//        cookie.setMaxAge(60);             //存活一分钟
//        cookie.setMaxAge(60*60);          //存活一小时
        cookie.setMaxAge(30 * 60);          //存活30分钟
//        cookie.setMaxAge(24*60*60);       //存活一天
//        cookie.setMaxAge(365*24*60*60);     //存活一年
        cookie.setPath("/");// 表示：整个网站都携带这个
        response.addCookie(cookie);
        // 跨域请求客户端服务器之间请求不携带cookies问题
        response.setHeader("Access-Control-Allow-Credentials", "true");
        return;
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     */
    @RequestMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {
        User user = userService.findByToken(token);
        if (user == null) {
            return "";
        }
        return user.getEmail();
    }

}
